<?php

namespace app\api\middleware;
use think\facade\Db;
use app\admin\model\User;
use think\Request;
use think\facade\Env;
use app\api\auth\User as UserAuth;


/**
 * API接口token验证中间件
 * Class AuthTokenMiddleware
 * @package app\http\middleware
 */
class TokenMiddleware 
{
    public function handle(Request $request, \Closure $next, bool $force = true)
    {
        $authInfo = null;
        $token    = trim($request->header('token'));
        $jwt = \Jwt::getInstance();
        $jwt->setKey(Env::get('TOKEN_KEY')); //设置秘钥 每个项目务必更换
        $jwt->setIss(Env::get('TOKEN_ISS'));  //签发者  可以写项目名或者开发者姓名
        $info= $jwt->verifyToken($token);
        if(!$info) return json(['code'=>-1,'msg'=>'token验证失败，请重新登录']);
        $user_token = $info['claim']['user_token'];
        try {
            $authInfo = Db::name('user')->where('token',$user_token)->find();
            if(!$authInfo) throw new \Exception("无效用户",-1);
        } catch (\Exception $e) {
            return json(['code'=>$e->getCode(),'msg'=>$e->getMessage()]);
        }
        // 绑定类
        bind('auth_user', UserAuth::class);
        // 信息初始化
        app('auth_user')->withId($authInfo['id'])->withData($authInfo)->setToken($info);
        return $next($request);
    }
}